<template>
  <ComDialog v-model="dialogVisible"
   :width="dialogWidth"
  :title="id ? '编辑' : '新增'">
    <ElementEasyForm ref="comFromRef" :formJson="formJson">
     <template #parentId v-if="formJson.model.parentId !== 0">
          <el-cascader
            :options="state.deptOptions"
            v-model="formJson.model.parentId"
            class="w100"
            :props="{
              checkStrictly: true,
              emitPath: false,
              value: 'deptId',
              label: 'deptName',
            }"
            clearable
            @change="handleCascader"
          />
        </template>
    </ElementEasyForm>
    <template #footer>
	<div >
			<el-button size="large" @click="handleClose">取消</el-button>
			<el-button size="large" :loading="subLoading" type="primary" @click="submitData">保存</el-button>
		</div>
    </template>
    	
  </ComDialog>
</template>

<script setup lang="tsx">
import { ref, reactive, defineEmits, onMounted, watch, shallowRef } from "vue";

import {
  getUser,
  addUser,
  updateUser,
  deptTreeSelect,
} from "/@ts/axios/urlApi/system/user";
import {
  getDept,
  addDept,
  updateDept,
  listDeptExcludeChild,
  listDept,
} from "/@ts/axios/urlApi/system/dept";
import { dialogWidth } from "/@ts/enums/sizeEnum";
import { ElMessage } from "element-plus";
import formatTool, { itemValue } from "/@ts/hooks/format";
import { hidden } from "element-easy-form/dist/drag-form/tool";
import { getConfigKey } from "/@ts/axios/urlApi/system/config";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { handleTree } = formatTool();
const emit = defineEmits(["update:modelValue","update"]);
const dialogVisible = shallowRef(false);
const subLoading = shallowRef(false);
const comFromRef = ref<any>();

const submitData = async () => {
  try {
    const res = await comFromRef.value.validate();
    if (props.id) {
      updateDept(res).then((resItem: any) => {
        ElMessage.success(t("操作成功"));
        handleClose();
        emit("update");
      });
    } else {
      addDept(res).then((resItem: any) => {
        ElMessage.success(t("操作成功"));
        handleClose();
        emit("update");
      });
    }
  } catch (error) {
    console.log("error :>> ", error);
  }
};
const state = reactive({
  deptOptions:[],
  postOptions:[],
  roleOptions:[],
  initPassword:""
});
const formJson = ref<any>({
  schema: [
    {
      label: "上级部门",
      prop: "parentId",
      colAttrs: {
        span: 24,
      },
      componentName: "ElCascader",
      attrs: {
        placeholder: "请选择上级部门",
      },
      hidden: {
        matchPattern: "&&",
        type: "function",
        value: false,
        dataJs: (config, data) => {
          return data.parentId === 0;
        }
      },
    },
    {
      label: "部门名称",
      prop: "deptName",
      colAttrs: {
        span: 12,
      },
      componentName: "ElInput",
      attrs: {
        placeholder: "请输入部门名称",
      },
      rules: [{ required: true, message: "部门名称不能为空", trigger: 'change' }],
    },
    {
      label: "显示排序",
      prop: "orderNum",
      colAttrs: {
        span: 12,
      },
      componentName: "ElInputNumber",
      attrs: {
        min: 0,
        placeholder: "请输入显示排序",
      },
      rules: [{ required: true, message: "显示排序不能为空", trigger: 'change' }],
    },
    {
      label: "负责人",
      prop: "leader",
      colAttrs: {
        span: 12,
      },
      componentName: "ElInput",
      attrs: {
        placeholder: "请输入负责人",
        maxlength: 20,
      },
    },
    {
      label: "联系电话",
      prop: "phone",
      colAttrs: {
        span: 12,
      },
      componentName: "ElInput",
      attrs: {
        placeholder: "请输入联系电话",
      },
      rules: [
        {
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: "请输入正确的手机号码",
          trigger: "blur",
        }
      ],
    },
    {
      label: "邮箱",
      prop: "email",
      colAttrs: {
        span: 12,
      },
      componentName: "ElInput",
      attrs: {
        placeholder: "请输入邮箱",
      },
      rules: [
        {
          type: "email",
          message: "请输入正确的邮箱地址",
          trigger: ["blur", "change"],
        }
      ],
    },
    {
      label: "部门状态",
      prop: "status",
      colAttrs: {
        span: 12,
      },
      componentName: "selectDict",
      attrs: {
        dictCode: "sys_normal_disable",
        placeholder: "请选择部门状态",
      },
    },
  ],
  rowAttrs: {
    gutter: 20,
    justify: "start",
    align: "middle"
  },
  model: {},
});
let props: any = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  id: {
    type: String,
    default: "",
  },
});
/** 查询部门下拉树结构 */
const getDeptTree = () => {
  deptTreeSelect().then((response: ResponseConfig) => {
    state.deptOptions = response.data;
  });
};


const getInfo = () => {

  getDept(props.id).then((response: ResponseConfig) => {
    formJson.value.model = response.data;

    listDeptExcludeChild(props.id).then((response: ResponseConfig) => {
      state.deptOptions = handleTree(response.data, "deptId");
      if (state.deptOptions.length == 0) {
        const noResultsOptions = {
          deptId: formJson.value.model.parentId,
          deptName: formJson.value.model.parentName,
          children: [],
        };
        state.deptOptions.push(noResultsOptions);
      }
    });
  });
};
watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val;
    if(props.id&&val){
        getInfo();
    }else if(!props.id&&val){
        listDept().then((response: ResponseConfig) => {
    state.deptOptions = handleTree(response.data, "deptId");
  });
      formJson.value.model = {
      };
    }
  },
  {
    immediate: true,
  }
);

const handleClose = () => {
  emit("update:modelValue", false);
};
watch(
  () => dialogVisible.value,
  (val) => {
    if (!val) {
      handleClose();
    }
  }
);
</script>

<style scoped lang="scss"></style>
